package com.yuewen.permissioncheck.asm.checker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhanglulu
 */
public class PermissionChecker {
  public static List<BasePermission> permissionList = new ArrayList<>();

  static {
    permissionList.add(new LocationServicesPermission());
    permissionList.add(new GetMacPermission());
    permissionList.add(new PhoneStatePermission());
    permissionList.add(new GetImeiPermission());
    permissionList.add(new GetHardwareAddressPermission());
    permissionList.add(new GetSubscriberIdPermission());
    permissionList.add(new GetDeviceIdPermission());
    permissionList.add(new GetLocationPermission());
  }


  public static String check(InvokeParam param) {
    for (BasePermission permission : permissionList) {
      if (permission.check(param)) {
        writePermissionToFile(param);
        return permission.invokeHookMethodName();
      }
    }
    return null;
  }

  private static boolean ignoreClass(String clazz) {
    return clazz.startsWith("android");
  }

  private static void writePermissionToFile(InvokeParam param) {
    writeLineToFile(param.methodName + "("+ param.methodParam +"), "
      + param.curClassName + "/" +param.curMethodName

    );
  }

  //----------------------------------------------------------------------------------------------
  // File 操作

  private static final File permissionFile = new File("permission_file.csv");
  private static BufferedWriter bufferedWriter;

  public static void initPermissionFile() {

    try {
      if (permissionFile.exists()) {
        permissionFile.delete();
      }
      permissionFile.createNewFile();
      FileWriter fileWriter = new FileWriter(permissionFile, true);
      bufferedWriter = new BufferedWriter(fileWriter);
      writeLineToFile("Method Name, Call location");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void closePermissionFile() {
    try {
      if (bufferedWriter != null) {
        bufferedWriter.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void writeLineToFile(String lineText) {
    try {
      BufferedWriter bw = PermissionChecker.bufferedWriter;
      if (bw == null) {
        return;
      }
      bw.write(lineText);
      bw.write("\n");
      bw.flush();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
